# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.models import User

import apps
from apps.post.models import Post
from apps.post.forms import PostForm
from apps.comment.forms import CommentForm

from django.http import Http404
#from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.db.models import F
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from apps.mainpage.myfilter import cut
from apps.tool.views import usepage

@login_required
def create(request, contype, conid):
    conname = getattr(apps, contype)
    conModel = getattr(conname.models, contype.capitalize())
    coninstance = conModel.objects.get(pk=conid)    
    if request.method == 'POST' and contype in["activity",]: 

        p = Post(author = request.user, master = coninstance )
        form = PostForm(request.POST, instance=p)
        if form.is_valid():
            form.save()
            coninstance.postcount = F('postcount') +1
            coninstance.save()
            return HttpResponseRedirect('/post/%s/' % (p.pk) )
        else:
            if form["title"].errors :
                form["title"].errors[0] = u"*必填"
            if form["content"].errors :
                form["content"].errors[0] = u"*必填"
            return render_to_response('post/create.html', {
                        'form': form,
                        'master': coninstance
                        },context_instance=RequestContext(request) )
    return render_to_response('post/create.html',{
                    'master': coninstance
                    },context_instance=RequestContext(request) )     
    
def list(request, contype, conid):
    if contype in["activity", ]:
        conname = getattr(apps, contype)
        conModel = getattr(conname.models, contype.capitalize())
        coninstance = conModel.objects.get(pk=conid)
        
        contypeid = ContentType.objects.get(model=contype).id
        postlist = Post.objects.select_related('author__username', 
            'author__userpic').filter(content_type=contypeid, 
            object_id=conid).order_by('-updatedtime',)
        postlist = usepage(postlist, 10, request)
        return render_to_response('post/list.html',{
            'postlist': postlist,
            'master': coninstance
            }, context_instance=RequestContext(request))
    raise Http404('没有论坛')

def read(request, id):
    post = Post.objects.get(pk=int(id))
    commentlist = post.comments.select_related('author').order_by('createdtime')
    commentlist = usepage(commentlist, 20, request)
        
    commentform = CommentForm(auto_id='comment_%s')
    return render_to_response('post/read.html',
        {'post': post, 
        'commentlist': commentlist,
        'commentform': commentform,
        'master': post.master # 活动信息边栏
        }, context_instance=RequestContext(request))

@login_required
def update(request, id):
    if request.user != Post.objects.get(pk=id).author:
        raise Http404('不具有该权限，或请先登录')
    if request.method == 'POST':
        post = Post.objects.get(pk=id)
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            p = form.save()
            return HttpResponseRedirect('/post/%s' % p.id )
        return render_to_response('post/create.html', {
                            'form': form,
                            'masterurl': post.master.get_absolute_url()
                            },context_instance=RequestContext(request) )  
    post = Post.objects.get(pk=id)
    form = PostForm({'title': post.title, 'content':post.content})
    return render_to_response('post/create.html', {
                    'form': form,
                    'master': post.master
                    },context_instance=RequestContext(request) )  


@login_required
def delete(request, id):
    if request.user != Post.objects.get(pk=id).author:
        raise Http404('不具有该权限，或请先登录')
    if 'makesure' in request.GET and request.GET['makesure']:
        post = Post.objects.get(pk=int(id))
        coninstance = post.master
        post.delete()
        
        coninstance.postcount = F('postcount') -1
        coninstance.save()   
        
        return HttpResponseRedirect(coninstance.get_absolute_url() )
    else:
        return render_to_response('post/delete.html', context_instance=RequestContext(request))


def main(request):
    return render_to_response('post/main.html', context_instance=RequestContext(request))
                    

    
